/**
 * CreateKwReply
 * @authors 杨兴洲（of2502）
 * @date    2017/5/26 0026 15:48
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */


import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {Popover, Form, Input, Button, message} from 'antd';
import GaUtil from "util/ga-util";
const FormItem = Form.Item;

@Relax
export default class CreateKwReply extends Component {


    static defaultProps = {
        kw_page: 1,
        kw_pageSize: 1,
        fetchKeywordReplyList: () => void 0,
        createKeywordReplyRule: () => void 0
    };

    componentDidMount() {

    }

    constructor(props) {
        super(props);
        this.state = {
            title: "未命名规则",
            visible: false
        };
    }

    render() {
        const content = (
            <Form inline>
                <FormItem>
                    <Input size="small" onChange={e => this.setState({title: e.target.value})}
                           value={this.state.title}/>
                </FormItem>
                <FormItem>
                    <Button size="small" type="primary" onClick={this.updateTitle}>确认</Button>
                </FormItem>
                <FormItem>
                    <Button size="small" onClick={this.hideTitlePopover}>取消</Button>
                </FormItem>
            </Form>
        );
        return (
            <div>
                <Popover placement="bottomLeft"
                         content={content}
                         visible={this.state.visible}
                         onVisibleChange={this.handleVisibleChange}
                         trigger="click">
                    <Button size="large" type="primary">新建回复</Button>
                </Popover>
            </div>
        );
    }

    handleVisibleChange = (visible) => {
        this.setState({visible});
    };

    hideTitlePopover = () => {
        let _this = this;
        this.setState({visible: false}, () => {
            _this.setState({title: '未命名规则'});
        })
    };

    updateTitle = async () => {
        const {kw_page: page, kw_pageSize: pageSize} = this.props;
        let title = this.state.title || '未命名规则';
        if (title.length > 30) {
            message.error("新建规则名称不能超过30个字");
            return;
        }
        await this.props.createKeywordReplyRule({
            rule_name: title,
            reply_mode: "random_one"
        });
        GaUtil.addEvent({eventAction: "新建关键词回复", eventLabel: "自动回复", eventValue: title});
        this.setState({visible: false, title: "未命名规则"});
        await this.props.fetchKeywordReplyList({page: 1, pageSize});
    };

}